package org.basis.advance.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * netty黏包半包演示server
 *
 * @author Mr_wenpan@163.com 2021/09/19 15:22
 */
@Slf4j
public class Server1 {

    public static void main(String[] args) throws InterruptedException {
        start();
    }

    public static void start() throws InterruptedException {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup woker = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, woker);

            // 调整系统的接收缓冲器大小（滑动窗口）
//            serverBootstrap.option(ChannelOption.SO_RCVBUF, 10);

            // 调整netty的接收缓冲区（byteBuf）大小，默认1024。
//            serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16));

            // 客户端channel连接后，为这些channel添加handler处理器
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加日志打印handler
                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                }
            });

            // 同步等待服务端绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error("server error ", ex);
        } finally {
            boss.shutdownGracefully();
            woker.shutdownGracefully();
        }
    }
}
